<?php
namespace app\admin\validate;

use think\facade\Db;

/**
 * 用户验证
 */
class Menu extends Main
{
    protected $rule = [
        'title' => 'require',
        'pid' => 'checkPid',
        'sort' => 'integer',
        'permission_id' => 'require'
    ];

    protected $message = [
        'title.require' => '请填写菜单名',
        'sort.integer' => '排序必须是整数',
        'permission_id.require' => '请选择权限',
        'permission_id.gt' => '必须选择一个权限'
    ];

    protected $scene = [
        'add' =>  ['title', 'pid', 'sort', 'permission_id'],
        'edit' => ['title', 'pid', 'sort', 'permission_id'],
        'del' => ['id']
    ];
    
    protected function checkPid($value, $rule, $data){
        if($value){
            if(!(new \app\admin\model\Menu)->value($value)){
                return '父ID错误';
            }
            if(empty($data['permission_id']) || ($data['permission_id'] == 0 && $data['pid'] != 0)){
                return '菜单必须选择一个权限';
            }
            if(!$permission = Db::name('permission')->where('id', $data['permission_id'])->find()){
                return '权限参数错误';
            }
            if($permission){
                $url = $permission['controller'].'/'.$permission['action'];
                $temp = Db::name('menu')->where('url', $url);
                if($data['id']??0){
                    $temp = $temp->where('id', '<>', $data['id']);
                }
                if($temp->find()){
                    return '菜单已存在'.($data['id']??0);
                }
            }
        }
        return true;
    }
}